package io.renren.modules.app.controller;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.domain.Sort.Order;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import io.renren.common.utils.PageUtils;
import io.renren.common.utils.R;
import io.renren.modules.app.entity.nosql.PdfInfo;
import io.renren.modules.app.nosql.mongo.IPdfRepo;
import io.renren.modules.app.temp.SpringDataPageable;
import io.renren.modules.job.task.TaskPdf;
import jodd.typeconverter.Converter;

@RestController
@RequestMapping("/app/pdf")
public class PdfController {

	@Autowired
	IPdfRepo pdfRepo;

	private Converter converter = Converter.get();
	
	@GetMapping("/info")
	@RequiresPermissions("app:pdf:list")
	public R info(@RequestParam Map<String, Object> params) {
		Optional<PdfInfo> findById = pdfRepo.findById(params.get("id").toString());
		if (!findById.isPresent()) {
			return R.error("没有找到该id");
		}
		return R.ok().put("pdfInfo", findById.get()).put("fastdfs", TaskPdf.fileServer);
	}

	@RequestMapping("/list")
	@RequiresPermissions("app:pdf:list")
	public R list(@RequestParam Map<String, Object> params) {
		List<Order> orders = new ArrayList<Order>();
		orders.add(new Order(Direction.DESC, "createTime"));

		SpringDataPageable pageable = this.getDataPageable(params, orders);
		pdfRepo.findAll(pageable);
		Page<PdfInfo> page = pdfRepo.findAll(pageable);

		PageUtils pageUtils = new PageUtils(page.getContent(), converter.toIntValue(page.getTotalElements()), page.getPageable().getPageSize(), page.getPageable().getPageNumber());
		return R.ok().put("page", pageUtils);
	}

	private SpringDataPageable getDataPageable(Map<String, Object> params, List<Order> orders) {
		SpringDataPageable pageable = new SpringDataPageable();
		pageable.setPagesize(converter.toIntValue(params.get("limit")));
		pageable.setPagenumber(converter.toIntValue(params.get("page")));
		pageable.setSort(Sort.by(orders));
		return pageable;
	}
}
